import java.io.IOException;
import java.net.*;
import java.util.Scanner;
public class UdpEchoClient {
    private DatagramSocket socket = null;
    private int serverPort;
    private String serverIP;
    public UdpEchoClient(String serverIP,int serverPort) throws SocketException {
        socket = new DatagramSocket();
        this.serverPort = serverPort;
        this.serverIP = serverIP;
    }
    public void start() throws IOException {
        System.out.println("客户端启动");
        Scanner scanner = new Scanner(System.in);
        while (true) {
           //输入请求
            System.out.println("请输入请求: ");
            String request = scanner.next();
            //构造请求
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),0,request.getBytes().length,
                    InetAddress.getByName(serverIP),serverPort);
            //发送请求
            socket.send(requestPacket);
            //构造接收的数据报
            DatagramPacket responsePack = new DatagramPacket(new byte[4096],4096);
            //接收服务器返回的结果
            socket.receive(responsePack);
            //转换成String类型
            String response = new String(responsePack.getData(),0, responsePack.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",9090);
        udpEchoClient.start();
    }
}
